#include "floatbutton.h"
#include <QGuiApplication>
#include <QScreen>
#include <QDebug>

FloatButton::FloatButton(QWidget *parent)
    : QPushButton{parent}
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    // setAttribute(Qt::WA_TranslucentBackground);
    raise();

    QString style = "QPushButton {"
                    "  background: url(:/icons/icon/logo.jpg);"
                    "  border: none;"
                    "}"
                    "QPushButton:hover {"
                    "  background: url(:/hover.png);"
                    "}"
                    "QPushButton:pressed {"
                    "  background: url(:/pressed.png);"
                    "}";
    setStyleSheet(style);
}

void FloatButton::mousePressEvent(QMouseEvent *e) {
    if (e->button() == Qt::LeftButton) {
        m_dragPos = e->globalPos() - geometry().topLeft();
        m_dragging = false;
        e->accept();
    }
    QPushButton::mousePressEvent(e);
}

void FloatButton::mouseMoveEvent(QMouseEvent *e) {
    if (e->buttons() & Qt::LeftButton) {
        m_dragging = true;
        move(e->globalPos() - m_dragPos);
        e->accept();
    }
    // QPushButton::mouseMoveEvent(e);
}

void FloatButton::mouseReleaseEvent(QMouseEvent *e) {
    if (e->button() == Qt::LeftButton) {
        if (!m_dragging) {
            QPushButton::mouseReleaseEvent(e);
        } else {
            QScreen *screen = QGuiApplication::primaryScreen();
            QRect screenRect = screen->geometry();

            int rightEdge = screenRect.right() - this->width();
            // 若靠近右侧边缘则吸附
            if (this->x() > rightEdge - 50) {
                move(rightEdge, this->y());
            }
            if (this->x() < 50) {
                move(0, this->y());
            }
            int bottomEdge = screenRect.bottom() - this->height();
            if (this->y() > bottomEdge - 50) {
                move(this->x(), bottomEdge);
            }
            if (this->y() < 50) {
                move(this->x(), 0);
            }
        }
        m_dragging = false;
    }
    e->accept();
}
